<template>
  <p-card :bordered="false" class="containent">
    <!-- 查询区域 -->
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper wrap1">
      <!-- 头部条码扫描 -->
      <p-row type="flex" :gutter="24">
        <p-col flex="auto">
          <p-form-model layout="inline" :model="topForm">
            <p-row :gutter="24">
              <p-col :xl="8" :md="12">
                <p-form-model-item label="条码扫描">
                  <p-input
                    placeholder="请扫描"
                    @pressEnter="afterScan"
                  ></p-input>
                </p-form-model-item>
              </p-col>
              <p-col :xl="8" :md="12">
                <p-form-model-item label="线体">
                  <p-select
                    v-model="topForm.lineno"
                    @change="changeLine"
                    allowClear
                  >
                    <p-select-option
                      v-for="item in lines"
                      :key="item.codeValue"
                      :value="item.codeValue"
                      >{{ item.textValue }}</p-select-option
                    >
                  </p-select>
                </p-form-model-item>
              </p-col>
              <p-col :xl="8" :md="12">
                <p-form-model-item label="工站">
                  <p-tree-select
                    v-model="topForm.stationCode"
                    :tree-data="stations"
                    :dropdown-style="{ maxHeight: '500px' }"
                    tree-node-filter-prop="title"
                    show-search
                    allow-clear
                    tree-default-expand-all
                    @change="changeHandler"
                  />
                </p-form-model-item>
              </p-col>
            </p-row>
          </p-form-model>
        </p-col>
        <p-col style="padding-top: 2px">
          <p-button type="primary" @click="setConfigVisible">配置项</p-button>
          <p-button class="ml10" type="primary" @click="resetScanResults"
            >重新扫描</p-button
          >
          <p-button type="primary" style="margin: 0 10px">容器绑定</p-button>
          <p-button type="primary">工序交接</p-button>
        </p-col>
      </p-row>
      <!-- 扫码信息 -->
      <div class="product-execu-title">
        <config-step
          ref="configStep"
          :current="currentStep"
          :type="scanType"
          class="float-right"
          style="width: auto; min-width: 50%"
          size="small"
          @success="setScanOrders"
          :station-code="topForm.stationCode"
        />
        扫码信息
      </div>
      <p-form-model
        layout="inline"
        :model="formSearch"
        :rules="rules"
        ref="Scan"
      >
        <p-row :gutter="24">
          <p-col :sm="8">
            <p-form-model-item label="地址码" prop="addressCode">
              <p-input
                readOnly
                placeholder=""
                v-model.trim="formSearch.addressCode"
              ></p-input>
            </p-form-model-item>
          </p-col>
          <p-col :sm="8">
            <p-form-model-item label="容器码" prop="containerCode">
              <p-input
                readOnly
                placeholder=""
                v-model.trim="formSearch.containerCode"
              ></p-input>
            </p-form-model-item>
          </p-col>
          <p-col :sm="8">
            <p-form-model-item label="接收人员" prop="acceptorName">
              <p-input
                readOnly
                placeholder=""
                v-model.trim="formSearch.acceptorName"
              ></p-input>
            </p-form-model-item>
          </p-col>
        </p-row>
      </p-form-model>
      <!-- 工序工单信息 -->
      <div class="product-execu-title">工序工单信息</div>
      <p-form-model layout="inline" :model="form" ref="Gd" :rules="rulesGd">
        <p-row :gutter="24">
          <p-col :sm="6">
            <p-form-model-item label="工序工单" prop="processbillNo">
              <p-select v-model="form.processbillNo" @change="changHandler">
                <p-select-option
                  v-for="(item, idx) in formList"
                  :key="idx"
                  :value="item.processbillNo"
                  >{{ item.processbillNo }}</p-select-option
                >
              </p-select>
            </p-form-model-item>
          </p-col>
          <p-col :sm="6">
            <p-form-model-item label="产品编码" prop="productCode">
              <p-input
                readOnly
                placeholder=""
                v-model="form.productCode"
              ></p-input>
            </p-form-model-item>
          </p-col>
          <p-col :sm="6">
            <p-form-model-item label="产品名称" prop="productName">
              <p-input
                readOnly
                placeholder=""
                v-model="form.productName"
              ></p-input>
            </p-form-model-item>
          </p-col>
          <p-col :sm="6">
            <p-form-model-item label="生产数量" prop="planQty">
              <p-input readOnly placeholder="" v-model="form.planQty"></p-input>
            </p-form-model-item>
          </p-col>
        </p-row>
      </p-form-model>
      <!-- 当前容器绑定清单 -->
      <div class="product-execu-title">
        <p-button class="float-right" type="primary" @click="containerOut"
          >出周转区</p-button
        >
        当前容器绑定清单
      </div>
      <div class="bottom-form">
        <p-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :pagination="false"
          :columns="columns"
          :dataSource="dataSource"
          :loading="loading"
          @change="handleTableChange"
          :rowSelection="{
            fixed: true,
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
          }"
        >
          <template slot="spilt" slot-scope="text, record">
            <p-input-number
              v-model="record.handOverQty"
              :max="record.pnsnQty"
              :min="1"
              :formatter="
                (value) => (value > record.pnsnQty ? record.pnsnQty : value)
              "
              :parser="
                (value) => (value > record.pnsnQty ? record.pnsnQty : value)
              "
              size="small"
              style="width: 50px"
            />
          </template>
        </p-table>
      </div>
    </div>
    <config
      ref="view"
      :type="scanType"
      v-model="configVisible"
      @success="onScanConfigSuccess"
      :station-code="topForm.stationCode"
    ></config>
  </p-card>
</template>

<script>
import { api } from "@/api/manage";
import { filterObj, timestampToDatetime } from "@/utils/util";
import { postAction, getAction, deleteAction } from "@/api/manage";
import ProcessList from "./modules/ProcessList";
import mixins from "./modules/line-station";
import configMixins from "./modules/configMixins";

//当前容器绑定清单
const columns = [
  {
    title: "序号",
    dataIndex: "",
    key: "rowIndex",
    width: 60,
    align: "center",
    customRender: function (t, r, index) {
      return parseInt(index) + 1;
    },
  },
  {
    title: "线体 ",
    align: "center",
    dataIndex: "lineName",
  },
  {
    title: "地址码",
    align: "center",
    dataIndex: "addressCode",
  },
  {
    title: "工序工单",
    align: "center",
    dataIndex: "processBillNo",
  },
  {
    title: "产品编码",
    align: "center",
    dataIndex: "productCode",
  },
  {
    title: "产品名称",
    align: "center",
    dataIndex: "productName",
  },
  {
    title: "PN/SN",
    align: "center",
    dataIndex: "pnsn",
  },
  {
    title: "组件编码",
    align: "center",
    dataIndex: "componentCode",
  },
  {
    title: "数量",
    align: "center",
    dataIndex: "pnsnQty",
  },
  {
    title: "交接数量",
    align: "center",
    dataIndex: "handOverQty",
    scopedSlots: { customRender: "spilt" },
  },
];
export default {
  name: "",
  mixins: [mixins, configMixins],
  components: {
    ProcessList,
  },
  data() {
    return {
      url: {
        getGZ: "/mes-craft/craft/mesPeDefinition/getAllStation", //获取工站
        getGxgd:
          "/mes-manufacture/mfContainer/getProcessBillForContainerHandover", //查询工序工单
        containerInfo:
          "/mes-manufacture/mfContainer/getContainerInfoByContainer", //获取容器相关信息
        containerOut: "/mes-manufacture/mfContainer/containerOutHandover", //出周转区
      },
      //工序工单信息
      form: {
        processbillId: "", //工序工单id
        processbillNo: "", //工序工单编码
        productCode: "", //产品编码
        productName: "", //产品名称
        planQty: "", //计划数量
      },
      formSearch: {},
      formList: [],
      size: "a",
      columns: [], //采集记录表格
      columns1: [], //右下角表
      dataSource: [], //当前容器绑定清单
      ipagination: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ["5", "10"],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      //扫描信息
      selectedRowKeys: [],
      selectionRows: [], //选中的record
      selectGD: [], //工单选择
      address: "",
      SN: "",
      operatorId: "",
      containerInfo: {}, //容器信息
      stationList: [], //工站
      loading: false,
      scanType: "Postexchange",
      rules: {
        addressCode: [
          { required: true, message: "请录入地址码", trigger: "blur" },
        ],
        containerCode: [
          { required: true, message: "请先扫描容器", trigger: "blur" },
        ],
        acceptorId: [
          { required: true, message: "请选择接收人", trigger: "blur" },
        ],
      },
      rulesGd: {
        processbillNo: [
          { required: true, message: "请选择工序工单", trigger: "change" },
        ],
      },
    };
  },
  watch: {
    // "formSearch.containerCode": function () {
    //   this.getContainerInfo();
    // },
  },
  computed: {},
  created() {
    this.columns = columns;
    this.getGxgd();
  },
  methods: {
    afterScan(event) {
      this.addScanResults(event);
      const len = this.scanResults.length;
      const code = this.scanResults[len - 1];
      const item = this.scanOrders[len - 1];
      switch (item.scanType) {
        case 3:
          this.formSearch.containerCode = code;
          this.getContainerInfo();
          break;
        case 4:
          this.formSearch.acceptorName = code;
          break;
        case 6:
          this.formSearch.addressCode = code;
          break;
      }
    },
    //过滤参数
    filterArg(arr) {
      let list = [];
      arr.map((item) => {
        let obj = {};
        obj.pnsn = item.pnsn;
        obj.pnsnQty = item.pnsnQty;
        obj.wipId = item.wipId;
        list.push(obj);
      });
      return list;
    },
    //获得工序工单
    getGxgd() {
      let params = {
        lineCode: 0,
        stationCode: "",
      };
      postAction(this.url.getGxgd, params).then((res) => {
        if (res.success) {
          this.formList = res.data || [];
        }
      });
    },
    //获得容器信息
    getContainerInfo(refresh) {
      let params = {
        containerCode: this.formSearch.containerCode,
      };
      this.loading = true;
      postAction(this.url.containerInfo, params)
        .then((res) => {
          if (res.success) {
            this.containerInfo = res.data;
            this.dataSource = res.data.childrens;
            this.dataSource.map((item) => {
              this.$set(item, "addressCode", res.data.addressCode);
              this.$set(item, "handOverQty", 1);
            });
            if (!refresh) {
              this.$message.success("扫描成功，请继续扫描地址码");
              // this.msg = "扫描成功";
              // this.msgType = "success";
              this.order = 1;
            }
          } else {
            this.$message.warning(res.msg);
            // this.msg = res.msg;
            // this.msgType = "warning";
            this.dataSource = [];
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //工单选择
    changHandler(val) {
      let item = this.formList.filter((item) => item.processbillNo === val);
      this.form.productCode = item[0].productCode;
      this.form.productName = item[0].productName;
      this.form.planQty = item[0].planQty;
      this.form.processbillId = item[0].processbillId;
    },
    changHandler1(val) {
      let item = this.stationList.filter((item) => item.processmcode == val);
      this.topForm.stationName = item[0].processmname;
    },
    //多选框
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
      console.log(this.selectionRows);
    },
    customResetScanResults() {
      this.formSearch = {};
      this.dataSource = [];
    },
    //出周转区
    containerOut() {
      this.$refs.Gd.validate((value) => {
        if (value) {
          if (!this.selectedRowKeys || this.selectedRowKeys.length == 0) {
            this.$message.warning("请先选中一条记录");
            // this.msg = "请先选中一条记录";
            // this.msgType = "warning";
            return false;
          }
          this.loading = true;
          let changenum = 0;
          let childs = this.selectionRows.map((item) => {
            changenum += item.handOverQty;
            let { handOverQty, pnsn, wipId, id } = item;
            return { handOverQty, pnsn, wipId, id };
          });
          let params = {
            ...this.formSearch,
            childs,
            containerCode: this.containerInfo.containerCode,
            containerNewQty: this.containerInfo.useQty - changenum,
            lineCode: this.topForm.lineno,
            lineName: this.topForm.lineName,
            stationCode: this.topForm.stationCode,
            stationName: this.topForm.stationName,
            processBillId: this.form.processbillId,
            processBillNo: this.form.processbillNo,
          };
          postAction(this.url.containerOut, params)
            .then((res) => {
              if (res.data) {
                this.$message.success("出周转区成功");
                // this.msg = "出周转区成功";
                // this.msgType = "success";
                this.getContainerInfo("refresh");
                this.selectedRowKeys = [];
              } else {
                this.$message.warning(res.msg);
                // this.msg = res.msg;
                // this.msgType = "warning";
              }
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
  },
};
</script>
